package com.fancon.android.gardenjokesx.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.fancon.android.gardenjokesx.GardenJokesBaseFragmentActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.GardenJokesActivity;
import com.fancon.android.gardenjokesx.adapter.JokesAdapter;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiService;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.gardenjokesx.widget.GardenControlView;
import com.fancon.android.gardenjokesx.widget.IRefresh;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.rpc.ApiCache;
import com.fancon.android.ui.widget.FanconProgressBar;

public class PopularFragment extends GardenJokesBaseFragment implements
		IRefresh {
	private static final String KEY_CONTENT = "JokesFragment:Content";
	private LayoutInflater mInflater;
	//private int index = 1;
	private View footerView;
	private ListView mGrid;
	//private Boolean isFirst = true;
	//private boolean loadingMore = false;
	//private ArrayList<Photo> listPhotos = new ArrayList<Photo>();
	//private Boolean isEnd = false;
//	private JokesAdapter adapter = null;
	private String currentUserId;
	private FanconProgressBar progress;
	public PopularFragment(GardenControlView topControl) {
		this.topControl = topControl;
	}

	public PopularFragment() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		User user = UserUtil.getInfoUserLogin(getActivity());
		currentUserId = user.getUser_id();
		// load();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			// We have different layouts, and in one of them this
			// fragment's containing frame doesn't exist. The fragment
			// may still be created from its saved state, but there is
			// no reason to try to create its view hierarchy because it
			// won't be displayed. Note this is not needed -- we could
			// just run the code below, where we would create and return
			// the view hierarchy; it would just never be used.
			return null;
		}

		adapter = null;
		if ((savedInstanceState != null)
				&& savedInstanceState.containsKey(KEY_CONTENT)) {
		}
		mInflater = LayoutInflater.from(container.getContext());
		View view = inflater.inflate(R.layout.list_page_layout, null);
		try {
			mGrid = (ListView) view.findViewById(R.id.lst_id);
			mGrid.setCacheColorHint(0);

			footerView = mInflater.inflate(R.layout.listfooter, null, false);
			mGrid.addFooterView(footerView);

			mGrid.setOnScrollListener(new OnScrollListener() {

				// useless here, skip!
				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
				}

				// dumdumdum
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {

					// what is the bottom iten that is visible
					int lastInScreen = firstVisibleItem + visibleItemCount;

					// is the bottom item visible & not loading more already ?
					// Load
					// more !
					if ((lastInScreen == totalItemCount) && !(loadingMore)
							&& (!isEnd) && (!isFirst)) {
						loadMore();
					}
				}
			});
			if (listPhotos == null
					|| (listPhotos != null && listPhotos.size() == 0)) {
				// load();
				loadFromCache();
			} else {
				loadDataView();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return view;
	}

	public void loadMore() {
		footerView.setVisibility(View.VISIBLE);
		index++;
		load();
	}

	public void loadFromCache() {
		try {
			LoadCacheRequest photoReq = new LoadCacheRequest(
					"photo_rq_cache", getActivity());
			((GardenJokesBaseFragmentActivity) getActivity()).getGlobalState()
					.getRequestQueue().addRequest(photoReq);
		} catch (Exception e) {
			Log.d("<<<<<", "Exception on popular");
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	public void load() {
		try {
			JokesRequest photoReq = new JokesRequest("photo_rq", getActivity());
			((GardenJokesBaseFragmentActivity) getActivity()).getGlobalState()
					.getRequestQueue().addRequest(photoReq);
		} catch (Exception e) {
			Log.d(">>>>>>", "Exception on popular");
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	private void loadDataView() {
		// isFirst for refresh
		if (listPhotos.size() > 0) {
			if (adapter == null || isFirst) {
				adapter = new JokesAdapter(getActivity(), listPhotos);
				mGrid.setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
		}else if(adapter == null){
			adapter = new JokesAdapter(getActivity(), listPhotos);
			mGrid.setAdapter(adapter);
		}
	}

	private void loadCacheDataView(ArrayList<Photo> tmp) {
		if (tmp.size() > 0) {
			adapter = new JokesAdapter(getActivity(), tmp);
			mGrid.setAdapter(adapter);
			firstPage.addAll(tmp);
		}
	}

	class JokesRequest extends RequestUI {
		private Activity context;
		// private FanconProgressBar progress;
		private ArrayList<Photo> tmp;

		public JokesRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			try {
				loadingMore = true;
				context = activity;
				if (isFirst) {
					if (topControl == null) {
						topControl = ((GardenJokesActivity) getActivity())
								.getTopControl();
					}
					topControl.showRefreshing();
					// ((IProgress)context).showProgress(context.getString(R.string.loading));
					// progress = FanconProgressBar.show(context,
					// context.getString(R.string.loading));
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void execute() throws Exception {
			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("user_id",
						currentUserId));
				nameValuePairs.add(new BasicNameValuePair("page_index", String
						.valueOf(index)));
				GardenJokesApiService api = new GardenJokesApiService(context,
						Constant.API_ROOT);
				String result = api.getApiData(
						"View/getListPopularPhotoDetailx",
						Constant.API_CACHE_POPULAR, nameValuePairs, false);
				Log.v("StringResult page" + index, result);
				JsonPaser jP = new JsonPaser();
				tmp = jP.getListPhotoDetail(result);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try {
				// ((IProgress)context).dismissProgress();
				footerView.setVisibility(View.GONE);

				topControl.showRefresh();
				 if (progress != null) {
				 //progress.dismiss();
				 }
				try {
					if (tmp.size() > 0) {
						if (listPhotos.size() > 0 && !isFirst) {
							listPhotos.addAll(tmp);
						} else {
							listPhotos = tmp;
							firstPage.clear();
							firstPage.addAll(tmp);
						}
					}
					if (tmp.size() == 0) {
						isEnd = true;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					isEnd = true;
				}
				loadDataView();
				loadingMore = false;
				isFirst = false;

			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			// Preload data
			PreLoadDataRequest photoReq = new PreLoadDataRequest(
					"photo_rq_pre", getActivity(), index + 1);
			((GardenJokesBaseFragmentActivity) getActivity()).getGlobalState()
					.getRequestQueue().addRequest(photoReq);
		}

	}

	class LoadCacheRequest extends RequestUI {
		private Activity context;
		private ArrayList<Photo> tmp = new ArrayList<Photo>();

		public LoadCacheRequest(Object key, Activity activity) {
			super(key, activity);
			this.context = activity;
			// TODO Auto-generated constructor stub
			try{
				 //progress = FanconProgressBar.show(context,
				 //context.getString(R.string.loading));
			}catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void execute() throws Exception {
			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("user_id",
						currentUserId));
				nameValuePairs.add(new BasicNameValuePair("page_index", "1"));
				GardenJokesApiService api = new GardenJokesApiService(context,
						Constant.API_ROOT);
				String result = api.getApiFromCache(
						"View/getListPopularPhotoDetailx",
						Constant.API_CACHE_POPULAR, nameValuePairs);
				Log.v("StringResult cache", result);
				JsonPaser jP = new JsonPaser();
				tmp = jP.getListPhotoDetail(result);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try{
			if(tmp.size() >0){
				//progress.dismiss();
			}
			load();
			loadCacheDataView(tmp);
			}catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

	}

	class PreLoadDataRequest extends RequestUI {
		private Activity context;
		private int index1;

		public PreLoadDataRequest(Object key, Activity activity, int index) {
			super(key, activity);
			this.context = activity;
			this.index1 = index;
			// TODO Auto-generated constructor stub
		}

		@Override
		public void execute() throws Exception {
			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("user_id",
						currentUserId));
				nameValuePairs.add(new BasicNameValuePair("page_index", String
						.valueOf(index1)));
				GardenJokesApiService api = new GardenJokesApiService(context,
						Constant.API_ROOT);
				String result = api.getApiData(
						"View/getListPopularPhotoDetailx",
						Constant.API_CACHE_POPULAR, nameValuePairs, index>3?true:false);
				Log.v("StringResult preload page" + index1, result);
				// JsonPaser jP = new JsonPaser();
				// tmpPhoto = jP.getListPhotoDetail(result);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
		}

	}

	@Override
	public void doRefresh(View v) {
		// TODO Auto-generated method stub
		ApiCache.clearApiCache(getActivity(), Constant.API_CACHE_POPULAR);
		isFirst = true;
		isEnd = false;
		index = 1;
		load();
	}

	@Override
	public void doLoad(View v) {
		// TODO Auto-generated method stub
		if (listPhotos == null
				|| (listPhotos != null && listPhotos.size() == 0)) {
			//load();
			loadFromCache();
		} else {
			loadDataView();
		}
	}

}
